package com.sy.nio.c1;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedDeque;

/**
 * @Author yumax
 * @Date 2024 01 06 09 37
 **/
@Slf4j
public class MultiThread {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("ssc");
        final ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8989));
        final Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT, null);

        Worker worker = new Worker("test1");

        while (true) {
            selector.select();
            final Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                final SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()) {
                    final SocketChannel sc = ssc.accept();

                    sc.configureBlocking(false);
                    log.debug("connected .. {}", sc.getRemoteAddress());
                    worker.register(sc);
                    //sc.register(worker.selector, SelectionKey.OP_READ, null);
                    log.debug(" after registed .. ");
                }
            }
        }
    }

    static class Worker implements Runnable {

        private Thread thread;
        private Selector selector;
        private String name;
        private volatile boolean isReg = false;
        private ConcurrentLinkedDeque<Runnable> queue = new ConcurrentLinkedDeque<>();

        public Worker(String name) {
            this.name = name;
        }

        public void register(SocketChannel sc) throws IOException {
            if (!isReg) {
                thread = new Thread(this, name);

                selector = Selector.open();
                isReg = true;
                thread.start();
            }
            queue.add(() -> {
                try {
                    sc.register(selector, SelectionKey.OP_READ, null);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
            selector.wakeup();
        }

        @Override
        public void run() {
            while (true) {
                try {
                    selector.select();
                    final Runnable task = queue.poll();
                    if (task != null) {
                        task.run();
                    }
                    final Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        final SelectionKey key = iterator.next();
                        iterator.remove();
                        if (key.isReadable()) {

                            final SocketChannel channel = (SocketChannel) key.channel();
                            final ByteBuffer buffer = ByteBuffer.allocate(16);
                            final int read = channel.read(buffer);
                            log.debug("readed .. {}", channel.getRemoteAddress());
                            if (read == -1) {
                                key.cancel();
                            } else {
                                buffer.flip();
                                ByteBufferUtil.debugAll(buffer);
                                buffer.clear();
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
